import sys
from PyQt5 import QtGui, QtCore
from PyQt5.QtCore import QThread, pyqtSignal
from PySide2.QtUiTools import QUiLoader
from PyQt5.QtWidgets import QApplication, QMessageBox, QTableWidgetItem, QFileDialog, QMainWindow
from GetHostIP import HostIP
import socket
from time import localtime

class Stats:
    def __init__(self):
        # 从文件中加载UI定义
        # 从 UI 定义中动态 创建一个相应的窗口对象
        # 注意：里面的控件对象也成为窗口对象的属性了
        # 比如 self.ui.button , self.ui.textEdit
        # http://www.b520.cc/2_2157/
        self.ui = QUiLoader().load('ui/appui2.ui')
        ip = HostIP().ip
        self.HPortStatus = 0
        self.DIPStatus = 0
        self.DPortStatus = 0

        self.udpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udpSocket.bind(('', 4433))

        self.ui.setWindowTitle("网络调试助手")
        self.ui.pushButton_2.setEnabled(False)  # 发送
        # self.ui.pushButton_3.setEnabled(False)  # 连接
        self.ui.pushButton_4.setEnabled(False)  # 保存
        self.ui.pushButton_3.clicked.connect(self.establishConnection)
        self.ui.pushButton_2.clicked.connect(self.sendData)
        self.ui.pushButton.clicked.connect(self.clearTextBrowser)
        self.ui.pushButton_5.clicked.connect(self.clearLineText)
        self.ui.pushButton_4.clicked.connect(self.saveLog)
        # self.ui.lineEdit_4.setText('192.168.0.104')
        # self.ui.lineEdit_3.setText('8800')

        self.threadRecv = RecvDataThread(self.udpSocket)
        self.threadRecv.sig.connect(self.recvData)

    def clearTextBrowser(self):
        self.ui.textBrowser.clear()

    def clearLineText(self):
        self.ui.lineEdit_5.clear()

    def infoCompleted(self):
        self.isDestPort()
        self.isDestIP()
        if self.DPortStatus * self.DIPStatus == 1:
            return True
        return False

    def establishConnection(self):
        if self.infoCompleted():
            self.ui.pushButton_2.setEnabled(True)
            self.ui.pushButton_4.setEnabled(True)
            self.ui.textBrowser.append("OK")
            self.threadRecv.start()

    def saveLog(self):
        mainWindow =  QMainWindow()
        msgBox = QMessageBox()
        filePath = QFileDialog.getSaveFileName(mainWindow, u'选择要保存的位置', './log.txt', '*')[0]
        log = str(self.ui.textBrowser.toPlainText())
        with open(filePath, "a") as f:
            f.write(log)
        QMessageBox.information(msgBox, '提示', '保存成功!')

    def isDestPort(self):
        dest_port = self.ui.lineEdit_3.text()
        if dest_port is not None and dest_port != '':
            self.DPortStatus = 1

    def isDestIP(self):
        dest_ip = self.ui.lineEdit_4.text()
        if dest_ip is not None and dest_ip != '':
            self.DIPStatus = 1

    def recvData(self, info):
        t = localtime()
        tStr = str(t.tm_hour)+':'+str(t.tm_min)+':'+str(t.tm_sec)
        info = eval(info)
        addr =  str(info[0]).replace('(', '[').replace(')', ']')
        data = info[1]
        self.ui.textBrowser.append(addr+'\t'+tStr)
        self.ui.textBrowser.append('>>'+data+'\n')

    def sendData(self):
        data = self.ui.lineEdit_5.text()
        dest_ip = self.ui.lineEdit_4.text()
        dest_port = int(self.ui.lineEdit_3.text())
        self.udpSocket.sendto(data.encode("gb2312"), (dest_ip, dest_port))

class RecvDataThread(QThread):
    sig = pyqtSignal(str)  # 自定义信号对象。参数str就代表这个信号可以传一个字符串
    def __init__(self, udpSocket):
        super(RecvDataThread, self).__init__()
        self.udpSocket = udpSocket
    def run(self):
        while True:
            rec_info = self.udpSocket.recvfrom(1024)
            # addr = '['+rec_info[1][0]+':'+str(rec_info[1][1])+']'
            addr = str(rec_info[1])
            data = rec_info[0].decode("gb2312")
            info = str([addr, data])
            if data:
                self.sig.emit(info)


if __name__ == '__main__':
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
    app = QApplication(sys.argv)
    stats = Stats()
    stats.ui.show()
    app.exec_()